import { createStore } from "vuex";

interface UserState {
  token: string | null;
  username: string | null;
}

export default createStore({
  state: {
    token: sessionStorage.getItem("token"),
    username: sessionStorage.getItem("username"),
  } as UserState,

  getters: {
    isAuthenticated: (state) => !!state.token,
    username: (state) => state.username,
  },

  mutations: {
    SET_TOKEN(state, token: string) {
      state.token = token;
      sessionStorage.setItem("token", token);
    },
    SET_USERNAME(state, username: string) {
      state.username = username;
      sessionStorage.setItem("username", username);
    },
    CLEAR_USER(state) {
      state.token = null;
      state.username = null;
      sessionStorage.removeItem("token");
      sessionStorage.removeItem("username");
    },
  },

  actions: {
    login({ commit }, { token, username }) {
      commit("SET_TOKEN", token);
      commit("SET_USERNAME", username);
    },
    logout({ commit }) {
      commit("CLEAR_USER");
    },
  },

  modules: {},
});
